# coding=utf-8

import web

import settings
import utils
from controllers.admin.widgets import destination_dropdown, destination_render
from controllers.admin.projects.forms import destination_form, project_form, tags_form
from controllers.admin.projects.models import Destination, Tag, Project
from controllers.admin.administrators import auth_login
from define import travel_type_text

render = settings.RENDER

class ProjectIndex(object):
    '项目管理首页'
    @auth_login
    def GET(self, id = '0'):
        q = web.input();
        # 判断是否启用精简模式
        if q.get('mode', False) == 'lite':
            return self.render_lite()
        else:
            # 完整模式
            f = project_form()
            return self.render(f, id)
    
    @auth_login
    def POST(self, id = '0'):
        f = project_form()
        if not f.validates():
            return self.render(f, id)
        else:
            id = utils.intval(id)
            if id <= 0:
                Project.add(f.name.value, f.type.value, f.dest_id.value)
            else:
                Project.update(id
                        , f.name.value
                        , f.type.value
                        , f.dest_id.value)

            # 跳转到项目管理首页
            raise web.seeother('/proj')

    def render_lite(self):
        """
        项目列表的精简模式
        """
        ipt = web.input(dest_id = '0', q = '')
        # 查询字符串
        query = ''
        # 目的地检索
        if ipt.dest_id != '0':
            dest_id = utils.intval(ipt.dest_id)
            if dest_id > 0:
                query += 'p.dest_id = ' + str(dest_id)
        # 关键词检索
        if ipt.q:
            if query:
                query += ' AND '
            query += "p.name LIKE '%" + ipt.q + "%'"
        # 补上 where
        if query:
            query = ' WHERE ' + query
        # 获取当前页码
        page = utils.intval(web.input().get('page', '0'))
        # 读取记录集
        r = Project.get_all(page * 15, 15, query)
        # 创建分页器
        pager = utils.Pager(r.totals, pageindex = page
                        , first = False, last = False
                        , link = '<a class="page-numbers" href="?mode=lite&page=%(page)s">%(text)s</a>&nbsp;'
                        , current = '<span class="page-numbers current">%(text)s</span>&nbsp;'
                        , next = '<a class="next page-numbers" href="?mode=lite&page=%(page)s">%(text)s</a>'
                        , prev = '<a class="prev page-numbers" href="?mode=lite&page=%(page)s">%(text)s</a>&nbsp;'
                        , nexttext = '»'
                        , prevtext = '«')
        # 创建目的地选择控件
        #dest_dropdown = destination_dropdown('dest_id'
        #        , dflt = u'- 目的地 -'
        #        , class_ = 'txt'
        #        , tabindex = 3)
        # 渲染模板
        return render.admin.projects.project_lite(r.result, pager, ipt.q)

    def render(self, form, id):
        # 获取要修改的记录
        dest_id = 0
        id = utils.intval(id)
        if id > 0:
            p = Project.get(id)
            if p:
                form.name.value = p.name
                form.type.value = str(p.type)
                dest_id = p.dest_id
                form.submit.attrs['html'] = u'修改项目'

        # 获取当前页码
        page = utils.intval(web.input().get('page', '0'))
        # 读取记录集
        r = Project.get_all(page * 15, 15)
        # 创建分页器
        pager = utils.Pager(r.totals, pageindex = page)
        # 创建目的地选择控件
        dest_dropdown = destination_dropdown('dest_id'
                , val = dest_id
                , class_ = 'txt'
                , tabindex = 3)
        # 渲染页面
        return render.admin.projects.project(form
                , r.result
                , dest_dropdown
                , travel_type_text
                , pager)

class TagsIndex(object):
    '标签管理'
    @auth_login
    def GET(self, id = '0'):
        # 标签添加表单
        f = tags_form()
        return self.render(f, id)

    @auth_login
    def POST(self, id = '0'):
        f = tags_form()
        if not f.validates():
            return self.render(f, id)
        else:
            id = utils.intval(id)
            if id <= 0:
                Tag.add(f.name.value)
            else:
                Tag.update(id, f.name.value)
                
            # 无论成功与否都跳转到标签页
            raise web.seeother('/tags')
    
    def render(self, form, id):
        # 标签内码转换为int
        id = utils.intval(id)
        if id > 0:
            # 读取给定标签
            tag = Tag.get(id)
            if tag:
                # 修改表单值
                form.name.value = tag.name
                form.submit.attrs['html'] = u'修改标签'

        # 读取所有标签
        tags = Tag.get_all()
        return render.admin.projects.tags(form = form, tags = tags)


class DestinationIndex(object):
    '目的地管理'
    @auth_login
    def GET(self, id = '0'):
        # 项目添加表单
        f = destination_form()
        return self.render(f, id)

    @auth_login
    def POST(self, id = '0'):
        f = destination_form()
        # 验证表单录入项
        if not f.validates():
            return self.render(f, id)
        else:
            id = utils.intval(id)
            if id <= 0:
                Destination.add(f.name.value
                        , f.parent.value
                        , f.type.value)
            else:
                Destination.update(id, f.name.value
                        , f.parent.value
                        , f.type.value)

            raise web.seeother('/dest')

    def render(self, form, id):
        # 转换编辑内码，如果有的话
        id = utils.intval(id)
        # 读取编辑项
        pval = None
        if id > 0:
            dest = Destination.get(id)
            if dest:
                # 父级
                pval = dest.parent_id
                # 给表单控件赋值
                form.name.value = dest.name
                form.type.value = str(dest.type)
                form.submit.attrs['html'] = u'更新目的地'

        # 获取带结构的目的地列表
        dests = Destination.get_with_depth()
        # 创建目的地选择控件
        dest_dropdown = destination_dropdown('parent'
                , dests
                , val = pval
                , class_ = 'txt'
                , tabindex = 2)
        # 生成列表html
        dests_render = destination_render(u'''
                        <tr>
                            <td>&nbsp;</td>
                            <td>%(name)s</td>
                            <td>%(type)s</td>
                            <td align="center"><a href="/admin/dest/edit/%(id)s">[编辑]</a>&nbsp;&nbsp;<a href="/admin/dest/delete/%(id)s" onclick="return confirm('当其下包含子级或其它从属信息时，将无法删除！确定删除吗？');" style="display:none;">[删除]</a></td>
                        </tr>
                    '''
                    , dests)
        return render.admin.projects.destination(form = form
                    , dests_render = dests_render
                    , dest_dropdown = dest_dropdown)
